<?php

namespace app\listeners;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class ExceptionListener
{
	public function onKernelException(GetResponseForExceptionEvent $event)
	{
		// 你可以从接收到的事件中，取得异常对象
		$exception = $event->getException();

		$message = sprintf(
			'My Error Exception: code: %s, message: %s',
			$exception->getCode(),
			$exception->getMessage()
		);

		//prin($message);

		// 自定义响应对象，来显示异常的细节
		$response = new Response();
		$response->setContent($message);

		// HttpExceptionInterface 是一个特殊类型的异常，持有状态码和头信息的细节
		if ($exception instanceof HttpExceptionInterface) {
			$response->setStatusCode($exception->getStatusCode());
			$response->headers->replace($exception->getHeaders());
		} else {
			$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
		}

		// 发送修改后的响应对象到事件中
		$event->setResponse($response);
	}
}